package Dao.Impl;

import Dao.AdminDAO;
import MyUtil.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class AdminDAOImpl implements AdminDAO {
    //声明变量
    private Connection adminDAOImplConn;
    private String sql;
    private PreparedStatement ps;
    private ResultSet rs;

    //构造方法
    public AdminDAOImpl() throws Exception {
        //获取连接
        adminDAOImplConn = JDBCUtils.getMyConnection();
    }

    //判断登录，成功true，失败false
    @Override
    public boolean administratorLogin(String username, String password) throws Exception {
        //查询SQL
        sql = "select * from admin where username =? and password = ?";
        ps = adminDAOImplConn.prepareStatement(sql);
        //占位符的赋值
        ps.setString(1,username);
        ps.setString(2,password);
        rs = ps.executeQuery();
        //判断结果
        if(rs.next()){
            return true;
        }
        //关闭资源
//         JDBCUtils.release(adminDAOImplConn,ps,rs);
        return false;
    }

    //注册管理员
    @Override
    public boolean administratorRegister(String username, String password) throws Exception {
        //增加sql语句
        sql = "insert into admin(username,password) values(?,?)";
        ps = adminDAOImplConn.prepareStatement(sql);
        ps.setString(1,username);
        ps.setString(2,password);
        int count = ps.executeUpdate();
        if (count!=0){
            return true;
        }
        return false;
    }

    //判断管理员用户名是否存在
    @Override
    public boolean checkAdminNameExist(String username) throws Exception {
        //查询SQL
        sql = "select * from admin where username = ?";
        ps = adminDAOImplConn.prepareStatement(sql);
        ps.setString(1,username);
        rs = ps.executeQuery();
        if (rs.next()){
            return true;
        }
        return false;
    }
}
